package storage

import (
	"context"
	"sync"
	"time"

	"github.com/it-sos/golibs/db/redis"
)

type redisClusterDb struct {
	db redis.GoLibRedisCluster
}

func (a redisClusterDb) GetExpire(key string) (time.Duration, error) {
	return a.db.TTL(context.Background(), key).Result()
}

func (a redisClusterDb) Get(key string) (string, error) {
	return a.db.Get(context.Background(), key).Result()
}

func (a redisClusterDb) Remove(key string) error {
	return a.db.Del(context.Background(), key).Err()
}

func (a redisClusterDb) Lock(key string, duration time.Duration) (bool, error) {
	return a.db.SetNX(context.Background(), key, true, duration).Result()
}

func (a redisClusterDb) Set(key, value string, duration time.Duration) error {
	return a.db.Set(context.Background(), key, value, duration).Err()
}

var instRedisCluster Storage
var onceRedisCluster sync.Once

func storeRedisCluster() Storage {
	onceRedisCluster.Do(func() {
		instRedisCluster = &redisClusterDb{
			redis.NewRedisCluster(),
		}
	})
	return instRedisCluster
}
